package com.nd.controller.wx;


import com.nd.pojo.bean.User;
import com.nd.pojo.bo.wx.UserRegisterBo;
import com.nd.pojo.vo.wx.BaseRespWXVo;
import com.nd.service.wx.UserRegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;


@RestController
@RequestMapping("wx")
public class WxRegisterController {

    @Autowired
    UserRegisterService userRegisterService;


    @RequestMapping("auth/regCaptcha")
    public BaseRespWXVo regCaptcha(@RequestBody User user, HttpServletRequest req){
        String mobile = user.getMobile();
        String msg = userRegisterService.regCaptcha(mobile);
        if(msg == null) return BaseRespWXVo.fail("验证码发送失败！");
        ServletContext servletContext = req.getServletContext();
        servletContext.setAttribute(mobile,msg);
        return BaseRespWXVo.ok("验证码发送成功！");
    }

    @RequestMapping("auth/register")
    public BaseRespWXVo register(@RequestBody UserRegisterBo userRegisterBo, HttpServletRequest req){
        ServletContext servletContext = req.getServletContext();
        String mobile = userRegisterBo.getMobile();
        String code = (String) servletContext.getAttribute(mobile);
        if(code==null) return BaseRespWXVo.fail("请先获取验证码！");
        if(!code.equals(userRegisterBo.getCode())) return BaseRespWXVo.fail("验证码错误!");
        Integer register = userRegisterService.register(userRegisterBo);
        if(register == 9999) return BaseRespWXVo.fail("该手机号已注册！");
        if(register == 9998) return BaseRespWXVo.fail("该用户名不可用");
        if(register == 10000) return BaseRespWXVo.fail("注册失败！");
        //注册成功销毁验证码
        servletContext.removeAttribute(mobile);
        return BaseRespWXVo.ok("注册成功！");
    }

    @RequestMapping("auth/reset")
    public BaseRespWXVo reset(@RequestBody UserRegisterBo userRegisterBo,HttpServletRequest req){
        ServletContext servletContext = req.getServletContext();
        String mobile = userRegisterBo.getMobile();
        String code = (String) servletContext.getAttribute(mobile);
        if(code==null) return BaseRespWXVo.fail("请先获取验证码！");
        if(!code.equals(userRegisterBo.getCode())) return BaseRespWXVo.fail("验证码错误!");
        Integer reset = userRegisterService.reset(userRegisterBo);
        if(reset == 9999) return BaseRespWXVo.fail("该手机号用户不存在，请注册！");
        if(reset == 10000) return BaseRespWXVo.fail("修改密码失败！");
        servletContext.removeAttribute(mobile);
        return BaseRespWXVo.ok("密码修改成功！");
    }
}
